<template>
  <div v-if="fileInfoIdFlag">
    <div class="crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item  :to="{ path: '/fileList' }">
          <i class="el-icon-lx-file"></i> 文件列表
        </el-breadcrumb-item>
        <el-breadcrumb-item>
          <i class="el-icon-lx-cascades"></i> 文件详情
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="container">
      <div class="handle-box">
        <el-button type="success" size="medium" icon="el-icon-plus" @click="handleAnalysis">数据统计配置</el-button>

        <el-button type="primary" size="medium" icon="el-icon-plus" @click="createConfig">AI模型配置</el-button>

        <el-button type="primary" size="medium" @click="handleAnalysisByHand">重新分析</el-button>
      </div>

      <el-table :data="tableData"
                border class="table"
                ref="fieldTable"
                header-cell-class-name="table-header"
                @selection-change="handleSelectChange"
                :row-style="tableRowStyle"
      >
        <el-table-column width="50" type="selection"></el-table-column>
        <el-table-column label="序号">
          <template #default="scope"><span>{{ scope.$index + 1 }}</span></template>
        </el-table-column>
        <el-table-column label="字段名">
          <template #default="scope"><span>{{ scope.row.fieldName }}</span></template>
        </el-table-column>
        <el-table-column label="取值类型">
          <template #default="scope">{{ scope.row.dataType }}</template>
        </el-table-column>
        <el-table-column label="空值率">
          <template #default="scope">{{ handleNullRate(scope.row.nullRate) }}</template>
        </el-table-column>
        <el-table-column label="众数">
          <template #default="scope">{{ scope.row.mode }}</template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination background layout="total, prev, pager, next" :current-page="query.pageIndex"
                       :page-size="query.pageSize" :total="pageTotal" @current-change="handlePageChange"></el-pagination>
      </div>
    </div>

    <el-dialog title="新建数据统计配置" v-model="analysisVisible" width="50%">
      <el-form label-position="left">
        <el-form-item label="配置名" required>
          <el-input v-model="analysisConfName"></el-input>
        </el-form-item>
        <el-alert type="info"
                  show-icon style="line-height: 20px; margin-bottom: 20px">不同方法仅适用于特定特征字段。<br>
                  皮尔森相关系数需要2个int/double字段，散点图可以传入2个字段，其他的方法只需一个字段。<br>除了数据分布可以传入string字段，其他方法请传入int/double字段。</el-alert>
      </el-form>
      <el-table :data="selectData" border class="table" size="small" header-cell-class-name="table-header">
        <el-table-column label="已选字段名">
          <template #default="scope"><span>{{ scope.row.fieldName }}</span></template>
        </el-table-column>
        <el-table-column label="字段类型">
          <template #default="scope"><span>{{ scope.row.dataType }}</span></template>
        </el-table-column>
      </el-table>
      <template #footer>
                <span class="dialog-footer">
                    <el-button @click="analysisVisible = false" size="medium">再想想</el-button>
                    <el-button type="primary" @click="createAnalysisConfig()" size="medium">确定</el-button>
                </span>
      </template>
    </el-dialog>

    <el-dialog title="新建AI模型配置" v-model="configCreate" width="50%">
      <el-form label-width="90px" label-position="left">
        <el-form-item label="配置名" required>
          <el-input v-model="form.name"></el-input>
        </el-form-item>

        <el-form-item label="模型类别" required>
          <el-select v-model="form.type" placeholder="学习类型" class="handle-select mr10">
            <el-option key="1" label="监督学习" value="SUPERVISED_LEARNING"></el-option>
            <el-option key="2" label="非监督学习" value="UNSUPERVISED_LEARNING"></el-option>
          </el-select>
          <el-alert type="info" description="您选择的最后一个字段为标签字段" v-if="form.type === 'SUPERVISED_LEARNING'"
                    show-icon style="height: 40px; margin-top: 10px"></el-alert>
          <el-alert type="info" description="没有目标字段,适用于k-means模型" v-if="form.type === 'UNSUPERVISED_LEARNING'"
                    show-icon style="height: 40px; margin-top: 10px"></el-alert>
        </el-form-item>

        <el-checkbox v-model="checked" style="margin-bottom: 20px">添加预测集文件</el-checkbox>
        <el-form-item label="选择文件" v-if="checked === true">
          <el-select v-model="useform.testFileInfoId" :label-width="120" placeholder="请选择您要使用的文件">
            <el-option
                    v-for="item in state.fileList.valueOf()"
                    :key="item.id"
                    :label="item.fileName"
                    :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-table :data="selectData" border class="table" header-cell-class-name="table-header" size="small"
                  v-if="form.type !== 'SUPERVISED_LEARNING'">
          <el-table-column label="已选字段名">
            <template #default="scope"><span>{{ scope.row.fieldName }}</span></template>
          </el-table-column>
          <el-table-column label="字段类型">
            <template #default="scope"><span>{{ scope.row.dataType }}</span></template>
          </el-table-column>
        </el-table>

        <el-table :data="selectData" border class="table" header-cell-class-name="table-header" size="small"
                  :row-style="AITableRowStyle" v-if="form.type === 'SUPERVISED_LEARNING'">
          <el-table-column label="已选字段名">
            <template #default="scope"><span>{{ scope.row.fieldName }}</span></template>
          </el-table-column>
          <el-table-column label="字段类型">
            <template #default="scope"><span>{{ scope.row.dataType }}</span></template>
          </el-table-column>
        </el-table>
      </el-form>
      <template #footer>
                <span class="dialog-footer">
                    <el-button @click="configCreate = false" size="medium">再想想</el-button>
                    <el-button type="primary" @click="saveConfig" size="medium">确定</el-button>
                </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {ref, reactive, onMounted} from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {GetAllFile, getFileDescribe, getFileDetail} from "../../api/file";
import {useRoute}from "vue-router";
import {useRouter}from "vue-router";
import {addConfig} from "../../api/config";
import {addAnalysisConfig} from "../../api/analysisConfig";

export default {
  name: "config",
  //训练特征
  setup() {
    const router=useRouter();
    const query = reactive({
      address: "",
      name: "",
      pageIndex: 1,
      pageSize: 10,
    });
    const route=useRoute()
    let fileInfoId = route.query.fileId;
    let fileInfoIdFlag = ref(false);
    let AnalysisMethodName=["数据分布","散点图","数据统计","偏度-峰度","皮尔森相关系数"];

    const tableData = ref([]);
    const selectData = ref([]);
    let analysisData=reactive([])
    const pageTotal = ref(0);
    let useform = reactive({
      testFileInfoId: null,
    });
    //let testFileInfoId = null;
    let checked=ref(false);
    let state = reactive({
      fileList: [],
    });

    const getFileList=()=>{
      GetAllFile(localStorage.getItem("ms_userId")).then(res=>{
        if(res.msg === '成功'){
          state.fileList=res.result;
        }
        else{
          ElMessage.error("获取文件列表失败!")
        }
      })
    };

    // 获取表格数据
    const getData = () => {
      const route=useRoute()
      if(fileInfoId!=='') {
        const payload ={
          fileInfoId: fileInfoId,
          userId: localStorage.getItem("ms_userId")
        }
        getFileDetail(payload).then(res => {
          if (fileInfoId === '0') {
            fileInfoIdFlag.value = true;
            tableData.value = [
              {
                dataType: "integer",
                fieldName: "模板编号",
                fileInfoId: 1,
                id: 177,
                mode: 12,
                nullRate: 0
              },
              {
                dataType: "integer",
                fieldName: "模板字段",
                fileInfoId: 1,
                id: 177,
                mode: 12,
                nullRate: 0
              }
            ];
          }
          else if (res.msg === "成功") {
            tableData.value = res.result.fileFields;
            pageTotal.value = tableData.value.length;
            fileInfoId=route.query.fileId;
            fileInfoIdFlag.value = true;
          }
        })
      }
    };

    // 查询操作
    const handleSearch = () => {
      query.pageIndex = 1;
      getData();
    };
    // 分页导航
    const handlePageChange = (val) => {
      query.pageIndex = val;
      getData();
    };

    // 表格编辑时弹窗和保存
    let analysisVisible = ref(false);
    let form = reactive({
      name: "",
      type: "",
      needLabel: "",
    });
    let analysisConfName = ref();

    const handleAnalysis = () => {
      if (selectData.value.length<1){
        ElMessage.warning("请选择需要的字段！");
        return ;
      }
      analysisVisible.value = true;
    };
    const createAnalysisConfig = () => {
      const payload={
        fileInfoId:selectData.value[0].fileInfoId,
        userId: localStorage.getItem("ms_userId"),
        configName:analysisConfName.value,
        chosenColumns:[],
      }
      if(payload.configName === undefined){
        ElMessage.warning("请输入配置名！")
        return
      }
        for(let i=0;i<selectData.value.length;i++){
          payload.chosenColumns.push(selectData.value[i].fieldName);
        }
        console.log("p"+JSON.stringify(payload))
      addAnalysisConfig(payload).then(res=>{
        console.log("r"+JSON.stringify(res))
        if(res.msg === '成功') {
          ElMessage.success(`已成功生成数据统计配置`);
          analysisVisible.value = false;
        }
        else ElMessage.error(`生成数据统计配置失败:`+res.msg);
      })
    };

    let resultVisible= ref(false);
    let featureTip=ref(0);
    let labelTip = ref(0);

    const configCreate = ref(false);
    const createConfig =() => {
      if (selectData.value.length<=1){
        ElMessage.warning("请选择至少两个字段！若为监督学习，最后选择的字段将作为标签");
        return ;
      }
      configCreate.value = true;
    };
    const saveConfig=()=>{
      console.log(checked.value);
      if (checked.value === false) {
        useform.testFileInfoId = null;
      }
      const payload={
        fileInfoId:selectData.value[0].fileInfoId,
        userId: localStorage.getItem("ms_userId"),
        learningType:form.type,
        configName:form.name,
        features:[],
        label: '',
        testFileInfoId: useform.testFileInfoId
      }
      if(payload.configName === "" || payload.learningType === "" ){
        ElMessage.warning("请输入必要信息！")
        return
      }
      if (form.type === 'UNSUPERVISED_LEARNING'){
        for(let i=0;i<selectData.value.length;i++){
          payload.features.push(selectData.value[i].fieldName);
        }
      }
      else{
        for(let i=0;i<selectData.value.length-1;i++){
          payload.features.push(selectData.value[i].fieldName);
        }
        payload.label = selectData.value[selectData.value.length-1].fieldName
      }
      console.log(payload.testFileInfoId)
      addConfig(payload).then(res=>{
        console.log(res)
        if(res.msg === '成功') {
          ElMessage.success(`已成功生成AI模型配置`);
          configCreate.value = false;
        }
        else ElMessage.error(`生成AI模型配置失败`+res.msg);
      })
    }

    let ids=ref([]);

    const handleSelectChange=val=>{
      selectData.value=val;
      ids = val.map(item => item.id);
      //console.log(ids)
    };

    const handleAnalysisByHand=()=>{
      ElMessage.warning(`重新分析文件中，请稍候`);
      const payload ={
        fileInfoId: fileInfoId,
        userId: localStorage.getItem("ms_userId")
      }
      getFileDescribe(payload)
        .then(res=>{
          ElMessage.success(`已成功重新分析文件`);
          setTimeout(() => {
            // 方法区
            location.reload();
          }, 2000);

        })
    };

    const handleNullRate=(val)=>{
      return val + "%";
    };

    const AITableRowStyle=(row)=> {
      let rowFont = {};
      if (row.rowIndex === selectData.value.length - 1) {
        rowFont.color = "red";
        return rowFont;
      } else {
        return '';
      }
    };

    const tableRowStyle=(row)=>{
      let arr = ids;
      let rowFont = {};
      if(row.row.id === arr[arr.length - 1]){
        rowFont.color = "red";
        return rowFont;
      }
    };

    onMounted(()=>{
      getData();
      getFileList();
    })

    return {
      query,
      fileInfoId,
      useform,
      //testFileInfoId,
      checked,
      state,
      fileInfoIdFlag,
      AnalysisMethodName,
      tableData,
      pageTotal,
      analysisVisible,
      resultVisible,
      form,
      analysisConfName,
      configCreate,
      createConfig,
      saveConfig,
      selectData,
      analysisData,
      featureTip,
      labelTip,
      getData,
      createAnalysisConfig,
      handleSelectChange,
      handleSearch,
      handlePageChange,
      handleAnalysis,
      handleNullRate,
      handleAnalysisByHand,
      AITableRowStyle,

      ids,
      tableRowStyle
    };
  },
};


</script>

<style scoped>
.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 300px;
  display: inline-block;
}
.table {
  width: 100%;
  font-size: 14px;
}
.red {
  color: skyblue;
}
.mr10 {
  margin-right: 10px;
}
.table-td-thumb {
  display: block;
  margin: auto;
  width: 40px;
  height: 40px;
}

</style>
